import Dialog from '../../../../lib/vant/dialog/dialog';
const util = require('../../../../utils/util.js');
const api = require('../../../../config/api.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    posters: { "isupload": false, "ip": "", "url": "", "isupdate": false, "size": 0 },//海报信息
    tabs: { "tabsActive": 0, "circleList": [], "baobeiList" :[]},
    addressOauhRefusedDialogShow: false,// 地理位置拒绝授权的弹窗
    audioOauhRefusedDialogShow: false,// 语音拒绝授权的弹窗
    linkAlbumInfoIndex: '',// 链接的下标
    appreciateInfo: {},//赞赏信息
    recommendInfo: {},// 推荐信息
    videoPopupShow: false,// 选择视频的弹出层
    imagePopupShow: false,// 选择图片的弹出层
    linkPopupShow: false,// 链接底部的选择弹出
    isOpenDiaShow: false,// 是否有弹窗显示
    linkErrorDialogShow: false,// 链接错误时的弹出
    id: "",// 专辑id
    albumTypeId: '', //专辑类型id
    albumTypeName: '', //专辑类型名称
    albumTitle: '',//词条名称
    albumTitleInputDisabled: true,// 词条名称是否可以禁止编辑
    albumSlogan: '',//词条宣传口号
    albumSloganInputDisabled: true,// 宣传口号是否可以禁止编辑
    albumAnnouncement: "",// 专辑公告
    albumEditorPeopleNumber: '',//专辑编辑人数
    isShowCatalog: false,//是否显示类目标签
    isDefaultPosters: true,// 是否为默认海报
    postersUrl: {},//海报图片url
    briefIntroduction: '',//简介
    briefIntroductionLength: 0,//简介字数
    recommendPopupShow: false,// 推荐圈子的popup是否展示
    voiceDialogShow: false,// 录音音频的dialog是否显示
    voiceDialogDeleteShow: false,// 删除编辑详情的dialog是否显示
    interestSetupDialogShow: false,// 未设置专辑费用的dialog是否显示
    albumInfoDeleteIndex: '',// 删除编辑详情的下标
    voiceUpdateIndex: '',// 录音音频修改标题的下标
    voiceUpdateTitle: '',// 录音音频修改标题
    albumInfo: [],// 专辑详情
    catalogId: '',//类目id
    catalogName: '',//类目name
    editorInChiefName: '',//主编名字
    editorInChiefImage: '',//主编头像
    isRecorderStart: false,//是否在开始录音
    nickName: "", // 当前用户昵称
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    _this.setData({
      nickName: app.globalData.logininfo.userInfo.nickName
    })
    // 页面加载信息
    _this.loadInfo(options);
    // 加载默认海报
    _this.getDefaultBackground();
    // 加载推荐圈子
    _this.loadRecommendedCircles();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    var posters = _this.data.posters;
    var isupdate = posters.isupdate;
    if (isupdate == true) {
      var postersUrl = { "size": posters.size, "ip": posters.ip, "url": posters.url };
      _this.setData({
        isDefaultPosters: !posters.isupload,// 是否为默认海报
        postersUrl: postersUrl,//海报图片url
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 类目标签页面
   */
  toSelectAlbumLabel: function(){
    wx.navigateTo({
      url: '../editorAlbumDetails/selectAlbumLabel/selectAlbumLabel',
    })
  },

  /**
   * 词条名称右边的编辑点击事件
   */
  albumTitleEditor: function(){
    var _this = this;
    _this.setData({
      albumTitleInputDisabled: false
    })
  },

  /**
   * 词条名称的input焦点移出事件
   */
  albumTitleInputBlur: function (e) {
    var _this = this;
    var albumTitle = e.detail.value;
    _this.setData({
      albumTitle: albumTitle,
      albumTitleInputDisabled: true
    })
  },

  /**
   * 宣传口号右边的编辑点击事件
   */
  albumSloganEditor: function () {
    var _this = this;
    _this.setData({
      albumSloganInputDisabled: false
    })
  },

  /**
   * 宣传口号的input焦点移出事件
   */
  albumSloganInputBlur: function (e) {
    var _this = this;
    var albumSlogan = e.detail.value;
    _this.setData({
      albumSlogan: albumSlogan,
      albumSloganInputDisabled: true
    })
  },

  /**
   * 页面加载信息
   */
  loadInfo: function (options) {
    var _this = this;
    var type = options.type;
    type = 0;
    var albumTitle = "";
    var albumSlogan = "";
    var albumTypeId = "";
    var albumTypeName = "";
    var editorInChiefName = "";
    var editorInChiefImage = "";
    if (type == 0){
      // 主编进行编辑
      var avatarUrl = app.globalData.logininfo.userInfo.avatarUrl;
      var nickName = app.globalData.logininfo.userInfo.nickName;
      var avatarip = app.globalData.logininfo.userInfo.avatarip;
      var avatarpath = app.globalData.logininfo.userInfo.avatarpath;
      albumTitle = options.albumTitle;
      albumSlogan = options.albumSlogan;
      albumTypeId = options.albumTypeId;
      albumTypeName = options.albumTypeName;
      editorInChiefName = nickName;
      editorInChiefImage = avatarpath == null || avatarpath.length <= 0 ? avatarUrl : avatarip+avatarpath;
    } else {
      // 其他人加入编辑
      var id = options.id;
    }

    var isShowCatalog = false;
    if (albumTypeName == "项目圈子专辑") {
      isShowCatalog = true;
    }
    _this.setData({
      albumTitle: albumTitle,
      albumSlogan: albumSlogan,
      albumTypeId: albumTypeId,
      albumTypeName: albumTypeName,
      isShowCatalog: isShowCatalog,
      editorInChiefName: editorInChiefName,
      editorInChiefImage: editorInChiefImage
    });
  },

  /**
   * 进入兴趣设置页面
   */
  toInterestSetup: function () {
    wx.navigateTo({
      url: '../editorAlbumDetails/interestSetup/interestSetup'
    })
  },

  /**
   * 专辑简介输入时事件
   */
  briefIntroductionInput: function (e) {
    var _this = this;
    var briefIntroduction = e.detail.value;
    var briefIntroductionLength = briefIntroduction.length;
    _this.setData({
      briefIntroduction: briefIntroduction,
      briefIntroductionLength: briefIntroductionLength
    })
  },

  /**
   * 推荐圈子简介输入时事件
   */
  tjTextareaBlur: function (e) {
    var _this = this;
    var desc = e.detail.value;
    _this.setData({
      ["recommendInfo.desc"]: desc
    })
  },

  /**
   * 播放或暂停动作
   */
  voiceBoFang: function (e) {
    var _this = this;
    var src = e.currentTarget.dataset.src;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["albumInfo[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = src;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["albumInfo[" + index + "].currentTime"]: 0,
          ["albumInfo[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name,
          ["albumInfo[" + index + "].startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["albumInfo[" + index + "].currentTime"]: backgroundAudioManager.currentTime,
          ["albumInfo[" + index + "].startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["albumInfo[" + index + "].voiceBoFangImage"]: api.AudioBoFangImage_Name
      });
    }
  },

  /**
   * 播放音乐（滚动条事件）
   */
  voiceSlider: function (e) {
    var _this = this;
    var position = e.detail.value;
    var src = e.currentTarget.dataset.src;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var voiceStartDate = util.digitalFormatTime(position);
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      //正在播放状态：不知道为什么，录音的在调用backgroundAudioManager.seek(Math.floor(position))方法无效，所以改成一下这种方式
      e.currentTarget.dataset.currenttime = position;
      e.currentTarget.dataset.voiceimage = api.AudioNoBoFangImage_Name;
      _this.voiceBoFang(e);
    } else {
      // 未播放状态
      _this.setData({
        ["albumInfo[" + index + "].currentTime"]: position,
        ["albumInfo[" + index + "].startDate"]: voiceStartDate
      });
    }
  },

  /**
   * 视频播放
   */
  videoPlay: function (e) {
    var _this = this;
    var videoId = e.currentTarget.dataset.id;
    this.videoContext = wx.createVideoContext(videoId);
    this.videoContext.pause();
  },

  /**
   * 跳转到视频播放页面
   */
  toVideo: function (e) {
    var _this = this;
    var src = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: '../../../../../../../video/video?state=0&type=3&id=&src=' + src
    })
  },

  /**
   * 是否展示音频dialog
   */
  voiceDialogShow: function (e) {
    var _this = this;
    var voiceDialogShow = _this.data.voiceDialogShow;
    var index = e.currentTarget == null ? e : e.currentTarget.dataset.index;
    var title = _this.data.albumInfo[index].title;
    if (voiceDialogShow) {
      // 关闭
      if (title.trim().length <= 0) {
        title = _this.data.nickName + "的音频"
      }
      _this.setData({
        isOpenDiaShow: false,
        voiceDialogShow: false,
        voiceUpdateIndex: "",
        ["albumInfo[" + index + "].title"]: title,
        voiceUpdateTitle: ""
      })
    } else {
      // 开启
      _this.setData({
        isOpenDiaShow: true,
        voiceDialogShow: true,
        voiceUpdateIndex: index,
        voiceUpdateTitle: title
      })
    }
  },

  /**
   * 音频dialog确认动作
   */
  voiceDialogConfirm: function () {

  }, 

  /**
   * 是否显示推荐圈子的popup
   */
  recommendPopupShow: function () {
    var _this = this;
    var recommendPopupShow = _this.data.recommendPopupShow;
    recommendPopupShow = !recommendPopupShow;
    _this.setData({
      recommendPopupShow: recommendPopupShow,
      isOpenDiaShow: recommendPopupShow
    })
  },

  /**
   * 兴趣专辑详情上移
   */
  albumLast: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    if(index == 0){
      // 第一个元素不能往前移动
      return false;
    }
    var isRecorderStart = _this.data.isRecorderStart;
    if (isRecorderStart) {
      // 录音中，不能上移
      return false;
    }
    var albumInfo = _this.data.albumInfo;
    albumInfo.splice(index - 1, 0, albumInfo[index]);
    albumInfo.splice(index + 1, 1);
    _this.setData({
      albumInfo: albumInfo
    })
  },

  /**
   * 兴趣专辑详情下移
   */
  albumNext: function (e) {
    var _this = this;
    var albumInfo = _this.data.albumInfo;
    var index = e.currentTarget.dataset.index;
    if (index + 1 == albumInfo.length) {
      // 第一个元素不能往后移动
      return false;
    }
    var isRecorderStart = _this.data.isRecorderStart;
    if (isRecorderStart) {
      // 录音中，不能下移
      return false;
    }
    albumInfo.splice(index + 2, 0, albumInfo[index]);
    albumInfo.splice(index, 1);
    _this.setData({
      albumInfo: albumInfo
    })
  },

  /**
   * 兴趣专辑详情删除:弹出dialog
   */
  albumDeleteDialogShow: function (e) {
    var _this = this;
    var albumInfoDeleteIndex = e.currentTarget.dataset.index;
    _this.setData({
      albumInfoDeleteIndex: albumInfoDeleteIndex,
      voiceDialogDeleteShow: true,
      isOpenDiaShow: true
    })
  },
  
  /**
   * 兴趣专辑详情关闭dialog
   */
  albumDeleteDialogClose: function (e) {
    var _this = this;
    if (e.detail == "confirm") {
      var albumInfoDeleteIndex = _this.data.albumInfoDeleteIndex;
      if (albumInfoDeleteIndex == "-1"){
        _this.setData({
          appreciateInfo: {},
        })
      } else if (albumInfoDeleteIndex == "-2") {
        _this.setData({
          recommendInfo: {},
        })
      } else {
        var albumInfo = _this.data.albumInfo;
        var albumType = albumInfo[albumInfoDeleteIndex].albumType;
        var state = albumInfo[albumInfoDeleteIndex].state;
        if (albumType == "3" && state == "1") {
          // 删除录音：因为录音会触发录音动作，需要先删除录音动作再进行删除view
          _this.setData({
            ["albumInfo[" + albumInfoDeleteIndex + "].isVoiceDialogShow"]: false
          })
          _this.doClearInterval();
          recorderManager.stop();
        }
        albumInfo.splice(albumInfoDeleteIndex, 1);
        _this.setData({
          albumInfo: albumInfo
        })
      }
    }
    _this.setData({
      albumInfoDeleteIndex: "",
      voiceDialogDeleteShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 编辑专辑详情
   */
  editorAlbumInfo: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var albumInfo = _this.data.albumInfo;
    var albumInfoLength = albumInfo.length;
    switch (type) {
      case "1":
        // 文字
        var info = {};
        info.albumType = type;
        info.focus = true;
        info.autoheight = true;
        info.value = "";
        albumInfo.push(info);
        _this.setData({
          albumInfo: albumInfo
        })
        break;
      case "2":
        // 图片
        _this.setData({
          imagePopupShow: true,
          isOpenDiaShow: true
        })
        break;
      case "3":
        // 音频
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.record']) {
              // 未授权
              wx.authorize({
                scope: 'scope.record',
                success() {
                  _this.recorderStart(albumInfo, albumInfoLength, type);
                },
                fail: function () {
                  // 拒绝授权
                  _this.setData({
                    audioOauhRefusedDialogShow: true,
                    isOpenDiaShow: true
                  })
                }
              })
            } else {
              // 已授权
              _this.recorderStart(albumInfo, albumInfoLength, type);
            }
          }
        })
        break;
      case "4":
        // 视频
        _this.setData({
          videoPopupShow: true,
          isOpenDiaShow: true
        })
        break;
      case "5":
        // 链接
        _this.setData({
          linkPopupShow: true,
          isOpenDiaShow: true
        })
        break;
      case "6":
        // 位置
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              // 未授权
              wx.authorize({
                scope: 'scope.userLocation',
                success() {
                  _this.albumInfoPositionStart(albumInfo, type);
                },
                fail: function () {
                  // 拒绝授权
                  _this.setData({
                    addressOauhRefusedDialogShow: true,
                    isOpenDiaShow: true
                  })
                }
              })
            } else {
              // 已授权
              _this.albumInfoPositionStart(albumInfo, type);
            }
          }
        })
        break;
      case "7":
        // 赞赏
        var appreciateInfo = {};
        appreciateInfo.state = 1;
        _this.setData({
          appreciateInfo: appreciateInfo
        })
        break;
      case "8":
        // 推荐
        _this.recommendPopupShow();
        break;
    }
  },

  /**
   * 开始录音
   */
  recorderStart: function (albumInfo, albumInfoLength, type) {
    var _this = this;
    var isPlay = false;//是否可以录音
    var albumTypeIsRecorderCount = 0;
    for (var i = 0; i < albumInfoLength; i++) {
      if (albumInfo[i].albumType == type) {
        albumTypeIsRecorderCount++;
        if (albumInfo[i].state == "2") {
          isPlay = true;
          break;
        }
      }
    }
    if (albumTypeIsRecorderCount == 0) {
      isPlay = true;
    }
    if (isPlay) {
      var info = {};
      info.albumType = type;
      info.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
      info.playState = "1";// 1正常录音  2暂停录音
      info.totalTime = 0;
      info.totalDate = "00:00";
      info.isVoiceDialogShow = true;
      albumInfo.push(info);
      _this.setData({
        albumInfo: albumInfo,
        isRecorderStart: true
      })

      const recorderOptions = {
        duration: util.getAudioFileMaxTime("albumInfo"),
        format: 'mp3'
      }
      //开始录音
      recorderManager.start(recorderOptions);

      // 定时器计算录音时间
      _this.doRecordInterval(albumInfoLength);

      // 录音结束
      recorderManager.onStop((res) => {
        _this.stopRecorderExecute(albumInfoLength, res);
      });

      // 录音中断
      recorderManager.onInterruptionBegin((res) => {
        recorderManager.stop();
        _this.setData({
          ["albumInfo[" + albumInfoLength + "].isVoiceDialogShow"]: false
        })
        _this.stopRecorderExecute(albumInfoLength, res);
      });
    }
  },
  
  /**
   * 开始录音
   */
  recorderStart2: function (index) {
    var _this = this;
    var info = {};
    info.albumType = 3;
    info.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    info.playState = "1";// 1正常录音  2暂停录音
    info.totalTime = 0;
    info.totalDate = "00:00";
    info.isVoiceDialogShow = true;
    _this.setData({
      ["albumInfo[" + index + "]"]: info,
      isRecorderStart: true
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("albumInfo"),
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doRecordInterval(index);

    // 录音结束
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(index, res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.setData({
        ["albumInfo[" + index + "].isVoiceDialogShow"]: false
      })
      _this.stopRecorderExecute(index, res);
    });

  },

  /**
   * 位置
   */
  albumInfoPositionStart: function (albumInfo, type){
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var value = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (value != null && value.length > 0){
          var info = {};
          info.albumType = type;
          info.value = value;
          info.latitude = latitude;
          info.longitude = longitude;
          info.address = address;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo
          })
        } else {
          util.dialogAlert("未选中有效地址")
        }
      }
    })
  },

  /**
   * 清除定时器
   */
  doClearInterval: function () {
    clearInterval(recordInterval);
    recordInterval = null;
  },

  /**
   * 定时器计算录音时间
   */
  doRecordInterval: function (index) {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var nowAlbumInfo = _this.data.albumInfo[index];
        var totalTime = nowAlbumInfo.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["albumInfo[" + index + "].totalTime"]: totalTime,
          ["albumInfo[" + index + "].totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 暂停录音
   */
  pauseRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["albumInfo[" + index + "].playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音
   */
  resumeRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["albumInfo[" + index + "].playState"]: "1"
    })
    recorderManager.resume();
    _this.doRecordInterval(index);
  },

  /**
   * 停止录音
   */
  stopRecorder: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.stopRecorderExecute(index, res);
    });
  },

  /**
   * 录音音频名称的修改
   */
  voiceUpdateTitle: function (e) {
    var _this = this;
    var title = e.detail;
    var index = _this.data.voiceUpdateIndex;
    if (title.trim().length <= 0){
      title = _this.data.nickName + "的录音音频";
    }
    _this.setData({
      ["albumInfo[" + index + "].title"]: title
    })
  },

  /**
   * 停止录音后的业务代码
   */
  stopRecorderExecute: function (index, tempFile) {
    var _this = this;
    _this.doClearInterval();
    var nowAlbumInfo = _this.data.albumInfo[index];
    if (nowAlbumInfo != null) {
      var isVoiceDialogShow = nowAlbumInfo.isVoiceDialogShow;
      if (isVoiceDialogShow) {
        var totalTime = parseInt(tempFile.duration / 1000);
        nowAlbumInfo.state = "2";
        nowAlbumInfo.src = tempFile.tempFilePath;
        nowAlbumInfo.title = "";
        nowAlbumInfo.currentTime = 0;
        nowAlbumInfo.totalTime = totalTime;
        nowAlbumInfo.fileSize = tempFile.fileSize;
        nowAlbumInfo.startDate = "00:00";
        nowAlbumInfo.totalDate = util.digitalFormatTime(totalTime);
        nowAlbumInfo.voiceBoFangImage = api.AudioNoBoFangImage_Name;
        _this.setData({
          ["albumInfo[" + index + "]"]: nowAlbumInfo,
        })
        _this.voiceDialogShow(index);
      }
    }
    _this.setData({
      isRecorderStart: false
    })
  },

  /**
   * 编辑详情文字的焦点移出事件
   */
  albumInfoTextareaInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["albumInfo[" + index + "].value"]: value
    })
  },

  /**
   * 编辑详情文字的焦点移出事件
   */
  albumInfoTextareaBlur: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var isSwitchEmoji = false;
    if (e.detail != null && e.detail.isSwitchEmoji != null) {
      isSwitchEmoji = e.detail.isSwitchEmoji;
    }
    if (!isSwitchEmoji) {
      _this.setData({
        ["albumInfo[" + index + "].focus"]: false,
        ["albumInfo[" + index + "].autoheight"]: false
      })
    }
  },

  /**
   * 编辑详情文字的聚焦事件
   */
  albumInfoTextareaFocus: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["albumInfo[" + index + "].focus"]: true,
      ["albumInfo[" + index + "].autoheight"]: true
    })
  },

  /**
   * 链接的焦点移出事件
   */
  albumInfoHrefInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["albumInfo[" + index + "].name"]: "",
      ["albumInfo[" + index + "].value"]: value,
      ["albumInfo[" + index + "].textareaPlaceholderShow"]: false
    })
    if (value.length <= 0) {
      _this.setData({
        ["albumInfo[" + index + "].textareaPlaceholderShow"]: true
      })
    }
  },

  /**
   * 链接的焦点移出事件
   */
  albumInfoHrefBlur: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var value = _this.data.albumInfo[index].value;
    _this.setData({
      ["albumInfo[" + index + "].focus"]: false
    })
    if (_this.checkLink(index) && value.length > 0) {
      _this.setData({
        linkNameDialogShow: true,
        isOpenDiaShow: true,
        linkAlbumInfoIndex: index
      })
    }
  },

  /**
   * 校验链接
   */
  checkLink: function (index) {
    var _this = this;
    var albumInfo = _this.data.albumInfo[index];
    var type = albumInfo.type;
    if (type == 1) {
      var value = albumInfo.value.trim();
      var reg = /^https:\/\/mp.weixin.qq.com*/;
      if (value.length > 0 && !reg.test(value)) {
        _this.setData({
          linkErrorDialogShow: true,
          isOpenDiaShow: true
        })
        return false;
      }
    }
    return true;
  },

  /**
   * 推荐项目确认动作
   */
  recommendConfirm: function () {
    var _this = this;
    var value = [];
    var circleList = _this.data.tabs.circleList;
    var baobeiList = _this.data.tabs.baobeiList;
    for (var i = 0; i < circleList.length; i++) {
      if (circleList[i].circlesChecked) {
        var valueInfo = {};
        valueInfo.id = circleList[i].id;
        valueInfo.title = circleList[i].title;
        valueInfo.peopleNumber = circleList[i].renshu;
        valueInfo.clockNumber = circleList[i].qiandao;
        valueInfo.money = circleList[i].showCirclesMoney;
        valueInfo.image = circleList[i].beijing;
        valueInfo.type = "1";//1圈子  2宝贝
        value.push(valueInfo);
      }
    }
    for (var i = 0; i < baobeiList.length; i++) {
      if (baobeiList[i].circlesChecked) {

      }
    }
    if (value.length > 0){
      var info = {};
      info.desc = "";
      info.value = value;
      _this.setData({
        recommendInfo: info
      })
    }
    _this.recommendPopupShow();
  },

  /**
   * 修改海报
   */
  updatepostersUrl: function () {
    wx.navigateTo({
      url: '../../../../ucenter/pages/background/background?type=1&title=设置专辑海报'
    })
  },
  
  /**
   * 提交校验
   */
  submitVerify: function () {
    var _this = this;
    var id = _this.data.id;
    var albumTypeId = _this.data.albumTypeId;//专辑类型id
    var albumTypeName = _this.data.albumTypeName;//专辑类型名称
    var catalogId = _this.data.catalogId;//类目id
    var albumTitle = _this.data.albumTitle;//词条名称
    var isDefaultPosters = _this.data.isDefaultPosters;//是否为默认海报
    var postersUrl = _this.data.postersUrl;//海报图片url
    var albumSlogan = _this.data.albumSlogan;//词条宣传口号
    var albumAnnouncement = _this.data.albumAnnouncement;// 专辑公告
    var albumEditorPeopleNumber = _this.data.albumEditorPeopleNumber;//专辑编辑人数
    var briefIntroduction = _this.data.briefIntroduction;// 专辑简介
    var albumInfo = _this.data.albumInfo;// 专辑详情
    var addrSize = 0;// 出现的地址信息次数
    var appreciatesCount = 0;// 出现的赞赏信息次数
    if (albumTypeName == "项目圈子专辑" && catalogId.length <= 0){
      util.dialogAlert("未选择类目标签");
      return false;
    }
    if (albumTitle.length <= 0) {
      util.dialogAlert("未填写词条名称");
      return false;
    }
    if (albumSlogan.length <= 0) {
      util.dialogAlert("未填写词条宣传口号");
      return false;
    }
    if (albumAnnouncement.length <= 0 || albumEditorPeopleNumber.length <= 0 || albumEditorPeopleNumber <= 0) {
      _this.interestSetupDialogShow();
      return false;
    }
    if (briefIntroduction.length <= 0) {
      util.dialogAlert("未填写专辑简介");
      return false;
    }
    if (albumInfo.length <= 0) {
      util.dialogAlert("未填写专辑详情");
      return false;
    }
    for (var i = 0; i < albumInfo.length; i++){
      switch (albumInfo[i].albumType) {
        case "1":
          // 文字
          var value = albumInfo[i].value.trim();
          if (value.length <= 0) {
            util.dialogAlert("请填写文字信息");
            return false;
          }
          break;
        case "5":
          // 链接
          var value = albumInfo[i].value.trim();
          if (value.length <= 0) {
            util.dialogAlert("请填写链接信息");
            return false;
          }
          if (!_this.checkLink(i)) {
            return false;
          }
          break;
        case "6":
          // 位置
          addrSize = addrSize + 1;
          break;
        case "7":
          // 赞赏
          appreciatesCount = appreciatesCount + 1;
          break;
      }
    }
    if (addrSize > 1) {
      util.dialogAlert("出现多个位置信息");
      return false;
    }
    if (appreciatesCount > 1) {
      util.dialogAlert("出现多个赞赏信息");
      return false;
    }
    return true;
  },

  /**
   * 上传所有文件
   */
  uploadFile: function (type) {
    var _this = this;
    var albumInfo = _this.data.albumInfo;
    var isDefaultPosters = _this.data.isDefaultPosters;//是否为默认海报
    var postersUrl = _this.data.postersUrl;//海报图片url
    var uploadInfoList = [];// 用来存放所有的上传内容

    // 先上传海报
    if (!isDefaultPosters) {
      var uploadInfo = {};
      uploadInfo.type = "1";
      uploadInfo.filePath = postersUrl.url;
      uploadInfoList.push(uploadInfo);
    }

    // 编辑详情
    for (var i = 0; i < albumInfo.length; i++){
      if (albumInfo[i].albumType == "2"){
        // 图片
        var tempFiles = albumInfo[i].tempFiles;
        for (var j = 0; j < tempFiles.length; j++) {
          var uploadInfo = {};
          uploadInfo.type = "2";
          uploadInfo.albumInfoIndex = i;
          uploadInfo.tempFilesIndex = j;
          uploadInfo.filePath = tempFiles[j].path;
          uploadInfoList.push(uploadInfo);
        }
      } else if (albumInfo[i].albumType == "3") {
        // 音频
        var uploadInfo = {};
        uploadInfo.type = "3";
        uploadInfo.albumInfoIndex = i;
        uploadInfo.filePath = albumInfo[i].src;
        uploadInfoList.push(uploadInfo);
      } else if (albumInfo[i].albumType == "4") {
        // 视频
        var uploadInfo = {};
        uploadInfo.type = "4";
        uploadInfo.albumInfoIndex = i;
        uploadInfo.filePath = albumInfo[i].src;
        uploadInfoList.push(uploadInfo);
      } else if (albumInfo[i].albumType == "5" && albumInfo[i].type == 2){
        // 链接
        var uploadInfo = {};
        uploadInfo.type = "5";
        uploadInfo.albumInfoIndex = i;
        uploadInfo.filePath = albumInfo[i].value;
        uploadInfoList.push(uploadInfo);
      }
    }
    if (uploadInfoList.length > 0){
      // 开始请求:要先上传
      _this.uploadFileQuery(uploadInfoList, 0, type);
    }else{
      _this.saveAlbumInfo(type);
    }
  },

  /**
   * 上传所有文件：执行请求
   */
  uploadFileQuery: function (data, queryIndex, type){
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "1":
        // 海报
        queryUrl = api.File_doImageUpload;
        break;
      case "2":
        // 图片
        queryUrl = api.File_doImageUpload;
        break;
      case "3":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
      case "4":
        // 视频
        queryUrl = api.File_doVideoUpload;
        break;
      case "5":
        // 链接
        queryUrl = api.File_doOtherUpload;
        break;
    }

    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "1"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "1":
              // 海报
              var postersUrl = _this.data.postersUrl;
              postersUrl.ip = ip;
              postersUrl.url = path;
              _this.setData({
                postersUrl: postersUrl
              });
              break;
            case "2":
              // 图片
              var albumInfoIndex = queryData.albumInfoIndex;// 编辑详情中的下标
              var tempFilesIndex = queryData.tempFilesIndex;// 图片里的下标
              _this.setData({
                ["albumInfo[" + albumInfoIndex + "].tempFiles[" + tempFilesIndex + "].ip"]: ip,
                ["albumInfo[" + albumInfoIndex + "].tempFiles[" + tempFilesIndex + "].path"]: path
              })
              break;
            case "3":
              // 音频
              var albumInfoIndex = queryData.albumInfoIndex;// 编辑详情中的下标
              _this.setData({
                ["albumInfo[" + albumInfoIndex + "].ip"]: ip,
                ["albumInfo[" + albumInfoIndex + "].src"]: path
              })
              break;
            case "4":
              // 视频
              var albumInfoIndex = queryData.albumInfoIndex;// 编辑详情中的下标
              var ffmpegvideoimagepath = data.result.ffmpegvideoimagepath;
              _this.setData({
                ["albumInfo[" + albumInfoIndex + "].ip"]: ip,
                ["albumInfo[" + albumInfoIndex + "].src"]: path,
                ["albumInfo[" + albumInfoIndex + "].ffmpegvideoimagepath"]: ffmpegvideoimagepath
              })
              if (_this.data.albumInfo[albumInfoIndex].totalTime <= 0) {
                var width = data.result.width;
                var height = data.result.height;
                var duration = data.result.duration;
                _this.setData({
                  ["albumInfo[" + albumInfoIndex + "].width"]: width,
                  ["albumInfo[" + albumInfoIndex + "].height"]: height,
                  ["albumInfo[" + albumInfoIndex + "].totalTime"]: duration,
                  ["albumInfo[" + albumInfoIndex + "].totalDate"]: util.digitalFormatTime(duration)
                })
              }
              break;
            case "5":
              // 链接
              var albumInfoIndex = queryData.albumInfoIndex;// 编辑详情中的下标
              _this.setData({
                ["albumInfo[" + albumInfoIndex + "].ip"]: ip,
                ["albumInfo[" + albumInfoIndex + "].value"]: path
              })
              break;
          }
        }
      },
      fail(res){
        // 失败
      },
      complete(res){
        // 结束：
        if (queryIndex < data.length - 1){
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex, type);
        }else{
          // 上传完成，执行save请求
          _this.saveAlbumInfo(type);
        }
      }
    })
  },

  /**
   * save请求
   */
  saveAlbumInfo: function (type) {
    var _this = this;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.access_token = res.access_token;
      data.openid = app.globalData.logininfo.openid;
      data.id = _this.data.id;
      data.typeId = _this.data.albumTypeId;//专辑类型id
      data.catalogId = _this.data.catalogId;//类目id
      data.title = _this.data.albumTitle;//词条名称
      data.postersIp = _this.data.postersUrl.ip;//海报图片的ip
      data.postersUrl = _this.data.postersUrl.url;//海报图片url
      data.slogan = _this.data.albumSlogan;//词条宣传口号
      data.announcement = _this.data.albumAnnouncement;// 专辑公告
      data.editorPeopleNumber = _this.data.albumEditorPeopleNumber;//专辑编辑人数
      data.briefintroduction = _this.data.briefIntroduction;// 专辑简介
      data.albumInfo = JSON.stringify(_this.data.albumInfo);// 专辑详情
      if (_this.data.appreciateInfo.state == 1) {
        data.appreciateInfo = JSON.stringify(_this.data.appreciateInfo);//赞赏信息
      }
      if (_this.data.recommendInfo.value != null && _this.data.recommendInfo.value.length > 0) {
        data.recommendInfo = JSON.stringify(_this.data.recommendInfo);// 推荐信息
      }
      data.state = type;
      util.post(api.Home_SaveOrUpdateAlbumInfoApiUrl, data).then(function (res) {
        if (res.code == 200) {
          util.dialogAlert("保存成功！");
          wx.hideLoading();
        }
      })
    })
  },

  /**
   * 提交服务器
   */
  submit: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 类型：1保存预览  2推广发布
      var type = e.currentTarget.dataset.type;
      // 校验
      if (_this.submitVerify()) {
        wx.showLoading({
          title: '保存中',
        })
        _this.uploadFile(type);
      };
    }
  },

  /**
   * 获取默认的专辑背景图片
   */
  getDefaultBackground: function(){
    var _this = this;
    var data = {};
    data.backgroundType = "1";
    data.isDefaultBackground = "1";
    util.post(api.Home_GetBackgroundUrl).then(function (res) {
      var postersUrl = { "size": "0", "ip": api.My_fetchImageRootUrl, "url": "/minicard/home/weekly/editorAlbumDetails/04haibao.png" };
      if (res.code == 200) {
        var list = res.result.list;
        if (list.length > 0) {
          var url = list[0].url;
          var ip = list[0].ip;
          postersUrl = { "size": "0", "ip": ip, "url": url }
        }
      }
      _this.setData({
        postersUrl: postersUrl
      })
    })
  },

  /**
   * 创建专辑需要设定参与专辑的人数弹窗关闭或打开
   */
  interestSetupDialogShow: function(e){
    var _this = this;
    var interestSetupDialogShow = !_this.data.interestSetupDialogShow;
    _this.setData({
      interestSetupDialogShow: interestSetupDialogShow,
      isOpenDiaShow: interestSetupDialogShow
    })
  },

  /**
   * 关闭链接的底部弹窗
   */
  linkPopupClose: function () {
    var _this = this;
    _this.setData({
      linkPopupShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 链接底部弹出的选择
   */
  linkSelect: function (e) {
    var _this = this;
    var albumInfo = _this.data.albumInfo;
    _this.linkPopupClose();
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      // 粘贴公众号文章链接
      var info = {};
      info.albumType = 5;
      info.type = 1;
      info.name = "";
      info.ip = "";
      info.value = "";
      info.focus = true;
      info.isShow = true;
      info.textareaPlaceholderShow = true;
      info.state = "1";
      albumInfo.push(info);
      _this.setData({
        albumInfo: albumInfo
      })
    } else if (type == 2) {
      // 从微信导入文件
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          var tempFile = res.tempFiles[0];
          var path = tempFile.path;
          var pathIndex1 = path.lastIndexOf(".");
          var pathIndex2 = path.length;
          var suffix = path.substring(pathIndex1 + 1, pathIndex2);//后缀名
          if (suffix == "doc" || suffix == "docx" || suffix == "pdf" || suffix == "xlsx" || suffix == "xls" || suffix == "ppt" || suffix == "pptx") {
            var info = {};
            info.albumType = 5;
            info.type = 2;
            info.name = tempFile.name;
            info.ip = "";
            info.value = tempFile.path;
            info.size = tempFile.size;
            info.state = "2";
            albumInfo.push(info);
            _this.setData({
              albumInfo: albumInfo
            })
          } else {
            util.dialogAlert("请选择doc、docx、xls、ppt、pdf、xlsx、pptx格式的文件");
          }
        }
      })
    }
  },

  /**
   * 关闭链接错误提示
   */
  linkErrorDialogClose: function () {
    var _this = this;
    _this.setData({
      linkErrorDialogShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 图片弹出层选择
   */
  imageSelect: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var albumInfo = _this.data.albumInfo;
    if (type == 1) {
      // 拍照
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['camera'],
        success(res) {
          var info = {};
          info.albumType = 2;
          info.state = "1";
          info.tempFiles = res.tempFiles;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo,
            imagePopupShow: false,
            isOpenDiaShow: false
          })
        }
      })
    } else if (type == 2) {
      // 从手机相册选择
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success(res) {
          var info = {};
          info.albumType = 2;
          info.state = "1";
          info.tempFiles = res.tempFiles;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo,
            imagePopupShow: false,
            isOpenDiaShow: false
          })
        }
      })
    } else if (type == 3) {
      //从微信导入图片
      wx.chooseMessageFile({
        count: 9,
        type: 'image',
        success(res) {
          var info = {};
          info.albumType = 2;
          info.state = "1";
          info.tempFiles = res.tempFiles;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo,
            imagePopupShow: false,
            isOpenDiaShow: false
          })
        }
      })
    }
  },

  /**
   * 视频弹出层选择
   */
  videoSelect: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var albumInfo = _this.data.albumInfo;
    if (type == 1) {
      // 拍摄
      wx.chooseVideo({
        sourceType: ['camera'],
        maxDuration: 60,
        camera: 'back',
        success(res) {
          var size = res.size;
          var width = res.width;
          var height = res.height;
          var duration = res.duration;
          var tempFilePath = res.tempFilePath;
          var id = "myVideo" + new Date().getTime();
          var totalDate = util.digitalFormatTime(duration);
          var info = {};
          info.id = id;
          info.size = size;
          info.width = width;
          info.height = height;
          info.albumType = 4;
          info.src = tempFilePath;
          info.totalTime = duration;
          info.totalDate = totalDate;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo,
            videoPopupShow: false,
            isOpenDiaShow: false
          })
        }
      })
    } else if (type == 2) {
      // 从手机相册选择
      wx.chooseVideo({
        sourceType: ['album'],
        maxDuration: 60,
        camera: 'back',
        success(res) {
          var size = res.size;
          var width = res.width;
          var height = res.height;
          var duration = res.duration;
          var tempFilePath = res.tempFilePath;
          var id = "myVideo" + new Date().getTime();
          var totalDate = util.digitalFormatTime(duration);
          var info = {};
          info.id = id;
          info.size = size;
          info.width = width;
          info.height = height;
          info.albumType = 4;
          info.src = tempFilePath;
          info.totalTime = duration;
          info.totalDate = totalDate;
          albumInfo.push(info);
          _this.setData({
            albumInfo: albumInfo,
            videoPopupShow: false,
            isOpenDiaShow: false
          })
        }
      })
    } else if (type == 3) {
      //从微信导入视频
      wx.chooseMessageFile({
        count: 1,
        type: 'video',
        success(res) {
          var tempFiles = res.tempFiles;
          for (var i = 0; i < tempFiles.length; i++) {
            var size = tempFiles[i].size;
            var tempFilePath = tempFiles[i].path;
            var id = "myVideo" + new Date().getTime() + i;
            var info = {};
            info.id = id;
            info.size = size;
            info.width = 0;
            info.height = 0;
            info.totalTime = 0;
            info.totalDate = "00:00";
            info.albumType = 4;
            info.src = tempFilePath;
            albumInfo.push(info);
          }
          _this.setData({
            albumInfo: albumInfo,
            videoPopupShow: false,
            isOpenDiaShow: false
          });
        }
      })
    }
  },

  /**
   * 关闭图片弹出层
   */
  imagePopupClose: function () {
    var _this = this;
    _this.setData({
      imagePopupShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 关闭视频弹出层
   */
  videoPopupClose: function () {
    var _this = this;
    _this.setData({
      videoPopupShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 预览图片
   */
  previewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var albumInfo = _this.data.albumInfo;
    var urls = [];
    var current = albumInfo[index].tempFiles[yindex].path;
    for (var i = 0; i < albumInfo.length; i++) {
      if (albumInfo[i].albumType == 2) {
        for (var y = 0; y < albumInfo[i].tempFiles.length; y++) {
          urls.push(albumInfo[i].tempFiles[y].path);
        }
      }
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
   * 公众号名称编辑事件
   */
  linkNameInput: function (e) {
    var _this = this;
    var name = e.detail.value;
    var index = _this.data.linkAlbumInfoIndex;
    _this.setData({
      ["albumInfo[" + index + "].name"]: name
    })
  },

  /**
   * 公众号名称弹窗关闭事件
   */
  linkNameDialogClose: function (e) {
    var _this = this;
    var index = _this.data.linkAlbumInfoIndex;
    var name = _this.data.albumInfo[index].name;
    if (name.length <= 0) {
      _this.setData({
        ["albumInfo[" + index + "].name"]: "公众号文章"
      })
    }
    _this.setData({
      linkNameDialogShow: false,
      isOpenDiaShow: true,
      linkAlbumInfoIndex: "",
      ["albumInfo[" + index + "].state"]: "2"
    })
  },

  /**
  * 跳转到视频播放页面：日记
  */
  navigateToWebView: function (e) {
    var text = e.currentTarget.dataset.text;
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '../../webView/webView?src=' + text,
      })
    } else {
      wx.openDocument({
        filePath: text,
        success: function (res) {
        }
      })
    }
  },

  /**
   * 语音拒绝授权的提示弹窗关闭
   */
  audioOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      audioOauhRefusedDialogShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 语音拒绝授权的提示弹窗确认动作
   */
  audioOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.record"] == true) {
          // 授权成功
          _this.audioOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.audioOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 语音拒绝授权的提示弹窗关闭
   */
  addressOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      addressOauhRefusedDialogShow: false,
      isOpenDiaShow: false
    })
  },

  /**
   * 语音拒绝授权的提示弹窗确认动作
   */
  addressOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.userLocation"] == true) {
          // 授权成功
          _this.addressOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.addressOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * tabs切换
   */
  tabsChange(event) {
    var _this = this;
    var index = event.detail.index;
    _this.setData({
      ["tabs.tabsActive"]: index
    })
  },

  /**
   * 加载推荐圈子
   */
  loadRecommendedCircles: function () {
    var that = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_getUserRecommendInfoApiUrl, data).then(res => {
          if (res.code == 200) {
            var json = res.result.json;
            that.setData({
              ["tabs.circleList"]: json.circleList,
              ["tabs.baobeiList"]: json.baobeiList
            })
          }
        })
      })
    }
  },

  /**
   * 推荐信息选中事件
   */
  recommendClick: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var circleList = _this.data.tabs.circleList;
    var baobeiList = _this.data.tabs.baobeiList;
    var count = 0;
    for (var i = 0; i < circleList.length; i++) {
      if (circleList[i].circlesChecked) {
        count = count + 1;
      }
    }
    for (var i = 0; i < baobeiList.length; i++) {
      if (baobeiList[i].circlesChecked) {
        count = count + 1;
      }
    }
    if (type == 1) {
      var circlesChecked = circleList[index].circlesChecked;
      if (!circlesChecked && count >= 3){
        return;
      }
      _this.setData({
        ["tabs.circleList[" + index + "].circlesChecked"]: !circlesChecked
      })
    } else if (type == 2) {
      var circlesChecked = baobeiList[index].circlesChecked;
      if (!circlesChecked && count >= 3) {
        return;
      }
      _this.setData({
        ["tabs.baobeiList[" + index + "].circlesChecked"]: !circlesChecked
      })
    }
  },

  /**
   * 清空录音
   */
  clearRecorder: function (e) {
    var _this = this;
    var albumInfo = _this.data.albumInfo;
    var albumInfoLength = albumInfo.length;
    var index = e.currentTarget.dataset.index;
    _this.doClearInterval();
    _this.setData({
      ["albumInfo[" + index + "].isVoiceDialogShow"]: false
    })
    recorderManager.stop();

    setTimeout(function () {
      // 音频
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.record']) {
            // 未授权
            wx.authorize({
              scope: 'scope.record',
              success() {
                _this.recorderStart2(index);
              },
              fail: function () {
                // 拒绝授权
                _this.setData({
                  audioOauhRefusedDialogShow: true
                })
              }
            })
          } else {
            // 已授权
            _this.recorderStart2(index);
          }
        }
      })
    }, 100)
  }
})